import hdfs
import glob
from hdfs import InsecureClient


class HdfsTools:

    def __init__(self, url='http://192.168.31.123:9870', user='hadoop'):
        self.url = url
        self.user = user
        self.client = InsecureClient(url, user)

    def ls(self, path='/'):
        return self.client.list(path)

    def mkdir(self, dirname):
        self.client.makedirs(dirname)
        return True

    def write(self, file_name, data, overwrite=False):
        self.client.write(hdfs_path=file_name, data=data, overwrite=overwrite)
        return True

    def upload(self, hdfs_path, local_path):
        self.client.upload(hdfs_path=hdfs_path, local_path=local_path)
        return True

    def is_exist(self, hdfs_path):
        return self.client.status(hdfs_path=hdfs_path, strict=False)

    def read(self, hdfs_path):
        with self.client.read(hdfs_path=hdfs_path) as f:
            return f.data.decode('utf-8')

    def delete(self, hdfs_path):
        self.client.delete(hdfs_path=hdfs_path)
        return True

    def rename(self, hdfs_path, new_name):
        self.client.rename(hdfs_src_path=hdfs_path, hdfs_dst_path=new_name)

    def download(self, hdfs_path, local_path, overwrite=True):
        self.client.download(hdfs_path=hdfs_path, local_path=local_path, overwrite=overwrite)
        return True






